package com.example;

import java.awt.*;
import java.awt.datatransfer.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ClipboardHttpServer {

    private static final int HTTP_PORT = 8000;

    public static void main(String[] args) throws IOException, URISyntaxException {
        // 创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();

        // 创建服务器Socket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open().bind(new InetSocketAddress(HTTP_PORT));
        System.out.println("HTTP Server started at http://localhost:" + HTTP_PORT);

        while (true) {
            // 接收客户端连接
            SocketChannel clientSocketChannel = serverSocketChannel.accept();

            // 将接收请求的任务提交到线程池处理
            executorService.submit(() -> {
                try {
                    handleRequest(clientSocketChannel);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

    private static void handleRequest(SocketChannel clientSocketChannel) throws IOException, URISyntaxException {
        // 读取请求
        ByteBuffer requestBuffer = ByteBuffer.allocate(1024);
        clientSocketChannel.read(requestBuffer);
        String request = new String(requestBuffer.array()).trim();
        URI uri = new URI(request.split(" ")[1]);

        // 只处理GET请求
        if (!"GET".equalsIgnoreCase(request.split(" ")[0])) {
            String errorMsg = "HTTP/1.1 405 Method Not Allowed\r\n" +
                    "Content-Type: text/plain\r\n" +
                    "Content-Length: 21\r\n" +
                    "\r\n" +
                    "Method Not Allowed\r\n";
            clientSocketChannel.write(ByteBuffer.wrap(errorMsg.getBytes()));
            return;
        }

        // 只处理根路径请求
        if (!uri.getPath().equals("/")) {
            String errorMsg = "HTTP/1.1 404 Not Found\r\n" +
                    "Content-Type: text/plain\r\n" +
                    "Content-Length: 13\r\n" +
                    "\r\n" +
                    "Not Found\r\n";
            clientSocketChannel.write(ByteBuffer.wrap(errorMsg.getBytes()));
            return;
        }

        // 获取剪切板中的文本内容
        String clipboardText = "";
        try {
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
                clipboardText = (String) clipboard.getData(DataFlavor.stringFlavor);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 返回响应
        String response = "HTTP/1.1 200 OK\r\n" +
                "Content-Type: text/plain\r\n" +
                "Content-Length: " + clipboardText.getBytes().length + "\r\n" +
                "\r\n" +
                clipboardText;
        clientSocketChannel.write(ByteBuffer.wrap(response.getBytes()));

        // 关闭连接
        clientSocketChannel.close();
    }
}